package com.igirl.manage.service.content;

import com.github.abel533.entity.Example;
import com.igirl.manage.pojo.ContentCategory;
import com.igirl.manage.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: jiaheng
 * @Description:
 * @Date: Created in 2017/12/31
 * @Modified:
 */
@Service
public class ContentCategoryService extends BaseService<ContentCategory>{

    @Override
    public List<ContentCategory> queryAll() {
        List<ContentCategory> categoryList = super.queryAll();
        return categoryList;
    }

    public ContentCategory saveCategoryAndUpdateParentCategory(ContentCategory contentCategory) {
        //成功标识
        Boolean flag = true;
        //获取父类是否是父节点
        ContentCategory parent = new ContentCategory();
        parent.setId(contentCategory.getParentId());
        parent.setIsParent(true);
        int count = super.queryCount(parent);
        if (count == 0) {
            Integer integer = super.updateSelective(parent);
            flag = integer == 1;
        }
        //保存分类
        contentCategory.setIsParent(false);
        //设置时间
        contentCategory.setCreated(new Date());
        contentCategory.setUpdated(new Date());
        //设置状态
        contentCategory.setStatus(1);
        //修改父分类状态
        if (flag) {
            Integer save = super.save(contentCategory);
            flag = save == 1;
        }
        if (flag) {
            return contentCategory;
        }
        return null;
    }

    public void deleteCategory(ContentCategory contentCategory) {
        //执行成功标识
        //所有要删除的节点
        List<Object> ids = new ArrayList<>();
        //获取所有要删除的节点
        deleteCategoryById(ids,contentCategory);
        Integer count = super.deleteByIds("id", ids);
        //获取自己父节点的子节点个数，如果为0，则修改状态
        ContentCategory category = new ContentCategory();
        category.setParentId(contentCategory.getParentId());
        List<ContentCategory> categoryList = super.queryListByWhere(category);
        if (categoryList.size() == 0) {
            ContentCategory parent = new ContentCategory();
            parent.setId(contentCategory.getParentId());
            parent.setIsParent(false);
            super.updateSelective(parent);
        }
    }


    public void deleteCategoryById(List<Object> ids,ContentCategory contentCategory) {
        ids.add(contentCategory.getId());
        //获取自己的子节点并删除
        ContentCategory category = new ContentCategory();
        category.setParentId(contentCategory.getId());
        List<ContentCategory> contentCategoryList = super.queryListByWhere(category);
        for (ContentCategory category1 : contentCategoryList) {
            if (category1.getIsParent()) {
                deleteCategoryById(ids,category1);
            }
            ids.add(category1.getId());
        }
    }
}
